package cn.k.shiro;


import cn.k.domain.Employee;
import cn.k.service.IEmployeeService;
import cn.k.service.IPermissionService;
import cn.k.service.IRoleService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {


    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.获取登录用户名
        String username = (String)token.getPrincipal();

        //2.以用户名为条件,查询数据库,获得用户对象
        Employee employee = employeeService.selectByUsername(username);

        //判断用户是否存在
        //将对象封装成info对象
        if (employee!=null){
            return  new SimpleAuthenticationInfo(
                    employee,
                    employee.getPassword(),
                    super.getName()
            );
        }

        return null;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
       /* //获取登录对象
        Employee employee = (Employee)principalCollection.getPrimaryPrincipal();

        //封装info对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //判断是否管理员
        if (employee.isAdmin()){
            info.addRole("admin");
            info.addStringPermission("*:*");
        }else {
            //用用户id,获取对应权限/角色
            //获取角色
            List<String> roles=roleService.queryRoleByEmployee(employee.getId());
            //根据用户id,获取到权限
            List<String> permissions =permissionService.selectByEmpId(employee.getId());


            info.addRoles(roles);
            info.addStringPermissions(permissions);
        }



        return info;*/
       return null;
    }


}
